package com.addzero.kmp.processor

import cn.hutool.core.io.FileUtil
import com.addzero.kmp.context.SettingContext
import com.addzero.kmp.context.SettingContext.settings
import com.google.devtools.ksp.processing.Resolver
import com.google.devtools.ksp.processing.SymbolProcessor
import com.google.devtools.ksp.processing.SymbolProcessorEnvironment
import com.google.devtools.ksp.processing.SymbolProcessorProvider
import com.google.devtools.ksp.symbol.KSAnnotated
import com.google.devtools.ksp.symbol.KSClassDeclaration


class JimmerEntityIsomorphicProcessor(
    private val environment: SymbolProcessorEnvironment
) : SymbolProcessor {

    //多轮编译要在成员用ret接收,如果在process直接收集map DDLContext则会覆盖元数据

//    val retEntitys = mutableSetOf<KSClassDeclaration>()


    override fun process(resolver: Resolver): List<KSAnnotated> {
        SettingContext.initialize(environment.options)
        println("ksp设置$settings")

        val entities = resolver.getSymbolsWithAnnotation("org.babyfish.jimmer.sql.Entity").filterIsInstance<KSClassDeclaration>()


        val isomorphicOutputDir = settings.isomorphicOutputDir
        //处理下包名
        val packageName = settings.isomorphicPackageName

        val replace = packageName.replace(".", "/")

        val absolutePath = FileUtil.file(isomorphicOutputDir, replace).absolutePath


        entities.forEach {
            generateIsomorphicDataClass(
                ksClass = it,
                outputDir = absolutePath,
                packageName = packageName,
                isomorphicClassSuffix = settings.isomorphicClassSuffix

            )
        }



//        retEntitys.addAll(entities)
        return emptyList()
    }

    override fun finish() {

//        ksClass: KSClassDeclaration,
//        outputDir: String = "shared/src/commonMain/kotlin/com/addzero/kmp/isomorphic",
//        generatedIsoClasses: MutableSet<String> = mutableSetOf<String>(), // 跟踪所有已生成同构体的FQCN
//        packageName: String = "com.addzero.kmp.isomorphic",
//        isomorphicClassSuffix: String="Iso", // 生成的同构体文件所在的包名


//        retEntitys.forEach {
//            generateIsomorphicDataClass(
//                ksClass = it,
//                outputDir = settings.isomorphicOutputDir,
//                packageName =settings.isomorphicPackageName,
//                isomorphicClassSuffix =
//                    settings.isomorphicClassSuffix
//
//            )
//        }

    }


}


/**
 * 处理器提供者
 */
class JimmerEntityIsomorphicProcessorProvider : SymbolProcessorProvider {
    override fun create(environment: SymbolProcessorEnvironment): SymbolProcessor {
        return JimmerEntityIsomorphicProcessor(environment)
    }

}
